﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Physis.Client.Controllers {

    public class ApplicationController : Controller { // PHISYS.CLIENT.WEB PROJECT 

        #region Protected Properties

        protected Models.ApplicationModel applicationModel = new Models.ApplicationModel ();

        #endregion


        #region Constructors

        public ApplicationController () {

            // RESERVED FOR FUTURE USE

            // NONE OF THE PROPRETIES ARE VALID AT CONSTRUCTION TIME, THIS HAPPENS AT INITIALIZE

            return;

        }

        #endregion 
        

        #region Overrides

        protected override void Initialize (System.Web.Routing.RequestContext requestContext) {

            base.Initialize (requestContext);


#if DEBUG 

            // VALIDATE GENERAL PERMISSIONS AND AUTHENTICATION 

            System.Diagnostics.Debug.WriteLine ("ApplicationController: " + Request.Url);

#endif


            if (applicationModel.Application.Session == null) {

                // USER NOT AUTHENTICATED OR NO SESSION AVAILABLE 

                String routeController = (RouteData.Values.ContainsKey ("controller")) ? RouteData.Values["controller"].ToString ().ToLower () : String.Empty;

                String routeAction = (RouteData.Values.ContainsKey ("action")) ? RouteData.Values["action"].ToString ().ToLower () : String.Empty;

                if (!((routeController == "home") && (routeAction == "login")) && (routeController != "permissiondenied")) {

                    // PUSH TO LOGIN PAGE IF NOT AUTHENTICATED, NO AUTOMATICA AUTHENTICATION THROUGH THIS CONTROLLER (UNLIKE THE ENTERPRISE ONE HAS/HAD)

                    Response.Redirect ("~/Home/Login", true);

                }

                else {

                    // ALLOW THE UNAUTHENTICATED TO PASS THROUGH TO THE LOGIN PAGE OR PERMISSION DENIED PAGE 

                }

            }

            return;

        }

        #endregion 

    }

}
